package jaux.tank.admin.modular.system.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import javax.annotation.Resource;
import javax.naming.NoPermissionException;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import jaux.tank.admin.config.properties.TankProperties;
import jaux.tank.admin.core.base.controller.BaseController;
import jaux.tank.admin.core.base.tips.Tip;
import jaux.tank.bean.annotion.core.BussinessLog;
import jaux.tank.bean.annotion.core.Permission;
import jaux.tank.bean.constant.Const;
import jaux.tank.bean.constant.factory.PageFactory;
import jaux.tank.bean.constant.state.ManagerStatus;
import jaux.tank.bean.core.ShiroUser;
import jaux.tank.bean.dictmap.UserDict;
import jaux.tank.bean.dto.UserDto;
import jaux.tank.bean.entity.system.User;
import jaux.tank.bean.enumeration.BizExceptionEnum;
import jaux.tank.bean.exception.TankException;
import jaux.tank.bean.vo.front.Ret;
import jaux.tank.bean.vo.front.Rets;
import jaux.tank.dao.system.UserRepository;
import jaux.tank.factory.UserFactory;
import jaux.tank.service.system.LogObjectHolder;
import jaux.tank.service.system.UserService;
import jaux.tank.service.system.impl.ConstantFactory;
import jaux.tank.shiro.ShiroKit;
import jaux.tank.utils.BeanUtil;
import jaux.tank.utils.MD5;
import jaux.tank.utils.StringUtils;
import jaux.tank.utils.ToolUtil;
import jaux.tank.utils.factory.Page;
import jaux.tank.warpper.UserWarpper;

/**
 * 系统管理员控制器
 *
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/mgr")
public class UserMgrController extends BaseController {

    private static String PREFIX = "/system/user/";

    @Resource
    private TankProperties tankProperties;
    @Autowired


    @Resource
    private UserRepository userRepository;
    @Autowired
    private UserService userService;

    /**
     * 跳转到查看管理员列表的页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "user.html";
    }

    /**
     * 跳转到查看管理员列表的页面
     */
    @RequestMapping("/user_add")
    public String addView() {
        return PREFIX + "user_add.html";
    }

    /**
     * 跳转到角色分配页面
     */
    //@RequiresPermissions("/mgr/role_assign")  //利用shiro自带的权限检查
    @Permission
    @RequestMapping("/role_assign/{userId}")
    public String roleAssign(@PathVariable String userId, Model model) {
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }

        userRepository.findById(userId).ifPresent(user->{
        	
        	model.addAttribute("userId", userId);
        	model.addAttribute("userAccount", user.getAccount());
        });
        return PREFIX + "user_roleassign.html";
    }

    /**
     * 跳转到编辑管理员页面
     */
    @Permission
    @RequestMapping("/user_edit/{userId}")
    public String userEdit(@PathVariable String userId, Model model) {
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        assertAuth(userId);
        this.userRepository.findById(userId)
        		.ifPresent(user->{
        			
        			model.addAttribute(user);
        			model.addAttribute("roleName", user.getRoleid()!=null?ConstantFactory.me().getRoleName(user.getRoleid()):null);
        			model.addAttribute("deptName", user.getDeptid()!=null?ConstantFactory.me().getDeptName(user.getDeptid()):null);
        			
        			LogObjectHolder.me().set(user);
        		});
        return PREFIX + "user_edit.html";
    }

    /**
     * 跳转到查看用户详情页面
     */
    @RequestMapping("/user_info")
    public String userInfo(Model model) {
    	Optional<ShiroUser> shiroUser = ShiroKit.getUser();
        if (!shiroUser.isPresent() ||ToolUtil.isEmpty(shiroUser.get().getId())) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
		userRepository.findById(shiroUser.get().getId()).ifPresent(user -> {
			model.addAttribute(user);
			model.addAttribute("roleName",
					user.getRoleid() != null ? ConstantFactory.me().getRoleName(user.getRoleid()) : null);
			model.addAttribute("deptName",
					user.getDeptid() != null ? ConstantFactory.me().getDeptName(user.getDeptid()) : null);
			LogObjectHolder.me().set(user);
		});
        return PREFIX + "user_view.html";
    }

    /**
     * 跳转到修改密码界面
     */
    @RequestMapping("/user_chpwd")
    public String chPwd() {
        return PREFIX + "user_chpwd.html";
    }

    /**
     * 修改当前用户的密码
     */
    @RequestMapping("/changePwd")
    @ResponseBody
    public Object changePwd(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) {
        if (!newPwd.equals(rePwd)) {
            throw new TankException(BizExceptionEnum.TWO_PWD_NOT_MATCH);
        }
        Optional<ShiroUser> shiroUser = ShiroKit.getUser();
        if(!shiroUser.isPresent()) {
        	throw new TankException(BizExceptionEnum.USER_NOT_EXISTED);
        }
		String userId = shiroUser.get().getId();
        User user = userRepository.findById(userId).orElse(null);
        if(user == null) {
        	throw new TankException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        String oldMd5 = MD5.md5(oldPwd, user.getSalt());
        if (user.getPassword().equals(oldMd5)) {
            String newMd5 = MD5.md5(newPwd, user.getSalt());
            user.setPassword(newMd5);
            userRepository.save(user);
            return SUCCESS_TIP;
        } else {
            throw new TankException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
        }
    }

    /**
     * 查询管理员列表
     */
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String name, 
    		@RequestParam(required = false) String beginTime, 
    		@RequestParam(required = false) String endTime, 
    		@RequestParam(required = false) String deptid,
    		@RequestParam(required = false) String roleId) {
        Map<String,Object> params = new HashMap<>();
        params.put("name",name);
        params.put("beginTime",beginTime);
        params.put("endTime",endTime);
        params.put("roleId",roleId);
        if (ShiroKit.isAdmin()) {
            User user = new User();
            if(!StringUtils.isNullOrEmpty(name)){
                user.setName(name);
                user.setAccount(name);
            }
            if(deptid!=null&&!deptid.equals("0")){
               params.put("deptid",deptid);
            }

            List<User> users = userService.findAll(params);
            return new UserWarpper(BeanUtil.objectsToMaps(users)).warp();
        } else {
            params.put("deptid",deptid);
            List<User> users = userService.findAll(params);

            return new UserWarpper(BeanUtil.objectsToMaps(users)).warp();
        }
    }
    /**
     * 查询管理员分页
     */
    @RequestMapping("/page")
    @Permission
    @ResponseBody
    public Object page(@RequestParam(required = false) String name,
    		@RequestParam(required = false) String beginTime, 
    		@RequestParam(required = false) String endTime, 
    		@RequestParam(required = false) String deptid,
    		@RequestParam(required = false) String roleId) {
    	Map<String,Object> params = new HashMap<>();
    	params.put("nameLike",name);
    	params.put("beginTime",beginTime);
    	params.put("endTime",endTime);
    	params.put("roleId",roleId);
    	if (ShiroKit.isAdmin()) {
    		  if(deptid!=null&&!deptid.equals("0")){
                  params.put("deptid",deptid);
               }
    		
    	} else {
    		params.put("deptid",deptid);
    	}
    	Page<User> users = userService.findPage(new PageFactory().defaultPage(),params);
    	Page<Map> page = new Page<>(users.getCurrent(), users.getSize(), users.getOrderByField(), users.isAsc());
    	page.setRecords((List<Map>) new  UserWarpper(BeanUtil.objectsToMaps(users.getRecords())).warp());
    	page.setTotal(users.getTotal());
    	return page;
    }

    /**
     * 添加管理员
     */
    @RequestMapping("/add")
    @BussinessLog(value = "添加管理员", key = "account", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Ret<String> add(@Valid UserDto user, BindingResult result) {
        if (result.hasErrors()) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }

        // 判断账号是否重复
        User theUser = userRepository.findByAccount(user.getAccount());
        if (theUser != null) {
            throw new TankException(BizExceptionEnum.USER_ALREADY_REG);
        }

        // 完善账号信息
        user.setSalt(ToolUtil.getRandomString(5));
        user.setPassword(MD5.md5(user.getPassword(), user.getSalt()));
        user.setStatus(ManagerStatus.OK.getCode());
        user.setCreatetime(new Date());

        return Rets.success(userRepository.save(UserFactory.createUser(user,new User())).getId());
    }

    /**
     * 修改管理员
     *
     * @throws NoPermissionException
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改管理员", key = "account", dict = UserDict.class)
    @ResponseBody
    public Ret<String> edit(@Valid UserDto user, BindingResult result) throws NoPermissionException {
        if (result.hasErrors()) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        User oldUser = userRepository.findById(user.getId()).orElse(null);
        if (ShiroKit.hasRole(Const.ADMIN_NAME)) {

            this.userRepository.save(UserFactory.updateUser(user,oldUser));
            return Rets.success(user.getId());
        } else {
            assertAuth(user.getId());
            Optional<ShiroUser> shiroUser = ShiroKit.getUser();
            if (shiroUser.isPresent() && shiroUser.get().getId().equals(user.getId()) ) {
                this.userRepository.save(UserFactory.updateUser(user,oldUser));
                return Rets.success(user.getId());
            } else {
                throw new TankException(BizExceptionEnum.NO_PERMITION);
            }
        }
    }

    /**
     * 删除管理员（逻辑删除）
     */
    @RequestMapping("/delete")
    @BussinessLog(value = "删除管理员", key = "userId", dict = UserDict.class)
    @Permission
    @ResponseBody
    public Tip delete(@RequestParam String userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能删除超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new TankException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }
        assertAuth(userId);
        userRepository.findById(userId).ifPresent(user->{
        	user.setStatus(ManagerStatus.DELETED.getCode());
        	userRepository.save(user);
        	
        });
        return SUCCESS_TIP;
    }

    /**
     * 查看管理员详情
     */
    @RequestMapping("/view/{userId}")
    @ResponseBody
    public User view(@PathVariable String userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        assertAuth(userId);
        return this.userRepository.findById(userId).orElse(null);
    }

    /**
     * 重置管理员的密码
     */
    @RequestMapping("/reset")
    @BussinessLog(value = "重置管理员密码", key = "userId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Tip reset(@RequestParam String userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        assertAuth(userId);
        userRepository.findById(userId)
        		.ifPresent(user->{
        			user.setSalt(ToolUtil.getRandomString(5));
        			user.setPassword(MD5.md5(Const.DEFAULT_PWD, user.getSalt()));
        			this.userRepository.save(user);
        		});
        return SUCCESS_TIP;
    }

    /**
     * 冻结用户
     */
    @RequestMapping("/freeze")
    @BussinessLog(value = "冻结用户", key = "userId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Tip freeze(@RequestParam String userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能冻结超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new TankException(BizExceptionEnum.CANT_FREEZE_ADMIN);
        }
        assertAuth(userId);
        userRepository.findById(userId).ifPresent(user->{
        	user.setStatus(ManagerStatus.FREEZED.getCode());
        	userRepository.save(user);
        	
        });
        return SUCCESS_TIP;
    }

    /**
     * 解除冻结用户
     */
    @RequestMapping("/unfreeze")
    @BussinessLog(value = "解除冻结用户", key = "userId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Tip unfreeze(@RequestParam String userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        assertAuth(userId);
        userRepository.findById(userId).ifPresent(user->{
        	user.setStatus(ManagerStatus.OK.getCode());
        	userRepository.save(user);
        	
        });
        return SUCCESS_TIP;
    }

    /**
     * 分配角色
     */
    @RequestMapping("/setRole")
    @BussinessLog(value = "分配角色", key = "userId,roleIds", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Tip setRole(@RequestParam("userId") String userId, @RequestParam("roleIds") String roleIds) {
        if (ToolUtil.isOneEmpty(userId, roleIds)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能修改超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new TankException(BizExceptionEnum.CANT_CHANGE_ADMIN);
        }
        assertAuth(userId);
        userRepository.findById(userId).ifPresent(user->{
        	user.setRoleid(roleIds);
        	userRepository.save(user);
        	
        });
        return SUCCESS_TIP;
    }

    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture) {
    	String uuid = UUID.randomUUID().toString();
        String pictureName = uuid + ".jpg";
        try {
            String fileSavePath = tankProperties.getFileUploadPath();
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
            throw new TankException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return uuid;
    }

    /**
     * 判断当前登录的用户是否有操作这个用户的权限
     */
    private void assertAuth(String userId) {
        if (ShiroKit.isAdmin()) {
            return;
        }
        List<String> deptDataScope = ShiroKit.getDeptDataScope();
        Optional<User> userOpt = this.userRepository.findById(userId);
        if(!userOpt.isPresent()) {
        	throw new TankException(BizExceptionEnum.NO_THIS_USER);
        }
        if (!deptDataScope.contains(userOpt.get().getDeptid())) {
            throw new TankException(BizExceptionEnum.NO_PERMITION);
        }

    }
}
